<?php

ignore_user_abort(true); 		// 后台运行，不受前端断开连接影响
set_time_limit(0); 				// 脚本将永久运行
chdir(dirname(__FILE__));
// error_reporting(E_ERROR);
require_once ("../../config.php"); // 引入配置
require_once ("../../log.php");
require_once ("../api_tool.php");
require_once ("core.php");

/**
 * @name 机器人拼多多发单Api接口
 * @desc 本接口列表，只是用于处理当前机器人行为
 */

// LOGINFO($_GET, "=== _GET");

// 获取商品数据
if ($_GET['shop_code'] == '1') {
	$shop_data = simQuery("SELECT * FROM item_ordinary WHERE item_id = {$_GET['shop_id']} AND channel_id = {$_GET['channel_id']};");		// 获取普通库
} else {
	$shop_data = simQuery("SELECT * FROM item_preferred WHERE item_id = {$_GET['shop_id']} AND channel_id = {$_GET['channel_id']};");		// 获取优选库
}

if (empty($shop_data)) {
	echo json_encode(array (
		'state' => -1,
		'msg'	=> '不是当前数据库查出的商品!',
	));
	exit();
}

$wx_data = simQuery("SELECT *, wx.id AS wx_id, wx.taobao_ance AS taobao_ance, wx.pdd_ance AS pdd_ance, wx.jd_ance AS jd_ance FROM wechat_group AS wx, robot AS bot WHERE wx.id = {$_GET['wx_id']} AND wx.robot_id = bot.id");
if (empty($wx_data)) {
	echo json_encode(array (
		'state' => -2,
		'msg'	=> '不存在当前微信群!',
	));
	exit();
}

// 查询是否有着商品号
$item_data = getPddDdkGoodsDetail($wx_data['pdd_ance'], "[{$shop_data['item_id']}]")['goods_details'][0];
if (empty($item_data)) {
	if ($_GET['shop_code'] == '2') {
		simQuery("DELETE FROM item_preferred WHERE id = {$_GET['shop_id']};");
	}
	echo json_encode(array (
		'state' => -3,
		'msg'	=> '不存在该商品!',
	));
	exit();
}

$resp = getPddDdkGoodsPromotionUrlGenerate($wx_data['pdd_ance'], "[{$shop_data['item_id']}]");
$Tpwd = $resp['goods_promotion_url_list'][0]['short_url'];

if (empty($Tpwd)) {
	if ($_GET['shop_code'] == '2') {
		simQuery("DELETE FROM item_preferred WHERE id = {$_GET['shop_id']};");
	}
	echo json_encode(array(
		'state' => -5,
		'msg'	=> '淘口令生成失败!',
	));
	exit();
}

$data = array();
foreach($shop_data as $key => $value) {
	if (!is_int($key) && !is_array($value) && !empty($value)) {
		$data[$key] = $value;
	}
}

foreach($item_data as $key => $value) {
	if (!is_int($key) && !is_array($value) && !empty($value)) {
		$data[$key] = $value;
	}
}

// 保存图片
foreach($item_data['goods_gallery_urls'] as $key => $value) {
	$data['goods_gallery_url'.$key] = $value;
}

foreach ($wx_data as $key => $value) {
	if (!is_int($key) && !is_array($value) && !empty($value)) {
		$data[$key] = $value;
	}
}

// 商品记录选取一下组合成数据发送
$data['good_img'] = $_GET['good_img'];
$host = "127.0.0.1";
$port = 80;
$url = "/api/api_pdd/send.php";
simQuery("UPDATE wechat_group SET wait_time = 0 WHERE id = {$wx_data['wx_id']}");
sendFZSHttp($host, $port, $url, $data);
echo json_encode(array(
	'state' => 1,
	'msg'	=> '成功!',
));

exit();
//分析整点时需要给所有正在工作的机器人
//$nowdate

?>